package com.ruoyi.background.service.impl;

import com.ruoyi.background.domain.AppSite;
import com.ruoyi.background.domain.AppSiteTopic;
import com.ruoyi.background.domain.AppSiteTopicUser;
import com.ruoyi.background.mapper.AppSiteTopicMapper;
import com.ruoyi.background.service.IAppSiteService;
import com.ruoyi.background.service.IAppSiteTopicService;
import com.ruoyi.background.service.IAppSiteTopicUserService;
import com.ruoyi.background.utils.CONFIG_KEY;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 站点题目Service业务层处理
 *
 * @author susu
 * @date 2024-08-27
 */
@Service
public class AppSiteTopicServiceImpl implements IAppSiteTopicService {
    @Autowired
    private AppSiteTopicMapper appSiteTopicMapper;

    @Autowired
    private IAppSiteTopicUserService siteTopicUserService;

    @Autowired
    private IAppSiteService appSiteService;

    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 查询站点题目
     *
     * @param id 站点题目主键
     * @return 站点题目
     */
    @Override
    public AppSiteTopic selectAppSiteTopicById(Long id) {
        return appSiteTopicMapper.selectAppSiteTopicById(id);
    }

    /**
     * 查询站点题目列表
     *
     * @param appSiteTopic 站点题目
     * @return 站点题目
     */
    @Override
    public List<AppSiteTopic> selectAppSiteTopicList(AppSiteTopic appSiteTopic) {
        return appSiteTopicMapper.selectAppSiteTopicList(appSiteTopic);
    }

    /**
     * 根据站点的id查询初始化好的
     *
     * @param id 站点的id
     * @return 结果
     */
    @Override
    public List<AppSiteTopic> selectTopicBySiteId(Long id) {
        //站点信息
        AppSite appSite = appSiteService.selectAppSiteById(id);
        AppSiteTopic appSiteTopic = new AppSiteTopic();
        List<AppSiteTopic> topics = appSiteTopicMapper.selectAppSiteTopicList(appSiteTopic);
        //取配置数据
        int topicTotal = topics.size();
        int topicConfigNum = Integer.parseInt(sysConfigService.selectConfigByKey(CONFIG_KEY.TOPIC_LEVEL_NUM));
        int max = Math.min(topicTotal, topicConfigNum); //最少几道题目
        List<Integer> topicIndex = new ArrayList<>();
        //取随机的的下标
        int randomNumber;
        do {
            randomNumber = (int) (Math.random() * topicTotal - 1);
            if (!topicIndex.contains(randomNumber)) {
                topicIndex.add(randomNumber);
            }
        } while (topicIndex.size() != max);
        List<AppSiteTopic> res = new ArrayList<>();
        for (Integer index : topicIndex) {
            AppSiteTopic topic = topics.get(index);
            topic.initTopic();
            topic.setSiteId(appSite.getId());
            topic.setSiteName(appSite.getName());
            res.add(topic);
        }
        return res;
    }

    /**
     * 新增站点题目
     *
     * @param appSiteTopic 站点题目
     * @return 结果
     */
    @Override
    public int insertAppSiteTopic(AppSiteTopic appSiteTopic) {
        appSiteTopic.setCreateTime(DateUtils.getNowDate());
        appSiteTopic.setCreateBy(SecurityUtils.getUsername());
        return appSiteTopicMapper.insertAppSiteTopic(appSiteTopic);
    }

    /**
     * 修改站点题目
     *
     * @param appSiteTopic 站点题目
     * @return 结果
     */
    @Override
    public int updateAppSiteTopic(AppSiteTopic appSiteTopic) {
        appSiteTopic.setUpdateTime(DateUtils.getNowDate());
        appSiteTopic.setUpdateBy(SecurityUtils.getUsername());
        return appSiteTopicMapper.updateAppSiteTopic(appSiteTopic);
    }

    /**
     * 批量删除站点题目
     *
     * @param ids 需要删除的站点题目主键
     * @return 结果
     */
    @Override
    public int deleteAppSiteTopicByIds(Long[] ids) {
        return appSiteTopicMapper.deleteAppSiteTopicByIds(ids);
    }

    /**
     * 删除站点题目信息
     *
     * @param id 站点题目主键
     * @return 结果
     */
    @Override
    public int deleteAppSiteTopicById(Long id) {
        return appSiteTopicMapper.deleteAppSiteTopicById(id);
    }

    /**
     * 用户提交答题
     *
     * @param topics 题目
     * @return 结果
     */
    @Override
    public Map<String, String> userAddTopic(List<AppSiteTopic> topics) {
        int total = topics.size();
        int trueSum = 0;
        for (AppSiteTopic topic : topics) {
            if (this.checkTopic(topic)) {
                topic.setIsTrue(0);
                trueSum++;
            } else {
                topic.setIsTrue(1);
            }
        }
        DecimalFormat df = new DecimalFormat("#.00");
        String accuracy = df.format((trueSum * 100L) / total);
        Map<String, String> res = new HashMap<>();
        res.put("total", String.valueOf(total));
        res.put("trueSum", String.valueOf(trueSum));
        res.put("siteName", topics.get(0).getSiteName());
        res.put("accuracy", accuracy);
        //插入用户的答题数据
        AppSiteTopicUser topicUser = new AppSiteTopicUser();
        topicUser.setUserId(SecurityUtils.getUserId());
        topicUser.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
        topicUser.setDeptId(SecurityUtils.getDeptId());
        topicUser.setSiteId(topics.get(0).getSiteId());
        topicUser.setSiteName(topics.get(0).getSiteName());
        topicUser.setTotalSum(total);
        topicUser.setTrueSum(trueSum);
        topicUser.setAccuracy(accuracy);
        topicUser.setIsAllRight(total == trueSum ? 0 : 1);
        siteTopicUserService.setUserTopicData(topics, topicUser);
        return res;
    }

    /**
     * 判断一道题目是否正确
     *
     * @param appSiteTopic 题目
     * @return true false
     */
    private boolean checkTopic(AppSiteTopic appSiteTopic) {
        if (appSiteTopic.getTopicType() == 1 || appSiteTopic.getTopicType() == 3) {
            //单选及判断 直接比较
            appSiteTopic.setUserAnsWerString((String) appSiteTopic.getUserAnswer());
            return appSiteTopic.getUserAnswer().equals(appSiteTopic.getTanser());
        } else if (appSiteTopic.getTopicType() == 2) {
            //用户答案
            List<String> res = (List<String>) appSiteTopic.getUserAnswer();
            StringBuilder answer = new StringBuilder();
            for (String re : res) {
                answer.append(re);
            }
            appSiteTopic.setUserAnsWerString(String.valueOf(answer));
            return String.valueOf(answer).equals(appSiteTopic.getTanser());
        }
        return false;
    }
}
